package com.min.monitor.os;

import com.min.common.util.ExactDecimalUtil;
import com.min.common.util.IpUtils;
import lombok.Data;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.CentralProcessor.TickType;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.Util;

import java.util.*;

@Data
public class ServerMonitor {
    private static final int OSHI_WAIT_SECOND = 1000;

    public Map<String,Object> getInfo() throws Exception {
        SystemInfo si = new SystemInfo();
        HardwareAbstractionLayer hal = si.getHardware();
        Map<String,Object> result = new HashMap<>();
        result.put("cpu", getCpuInfo(hal.getProcessor()));
        result.put("memory", getMemoryInfo(hal.getMemory()));
        result.put("disk", getDiskInfo(si.getOperatingSystem()));
        result.put("os", getSystemInfo());
        result.put("jvm", getJvmInfo());
        return result;
    }

    /**
     * cpu 信息
     * @param processor:
     * @return: com.min.monitor.os.Cpu
     * @author: fengt
     * @date: 2021/7/19 15:54
     **/
    private Cpu getCpuInfo(CentralProcessor processor) {
        Cpu cpu = new Cpu();
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        Util.sleep(OSHI_WAIT_SECOND);
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
        long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
        long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
        long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
        long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
        long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
        long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
        long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
        cpu.setCore(processor.getLogicalProcessorCount());
        cpu.setTotal(totalCpu);
        cpu.setSys(cSys);
        cpu.setUsed(user);
        cpu.setWait(iowait);
        cpu.setFree(idle);
        return cpu;
    }

    /**
     * 内存信息
     * @param m:
     * @return: com.min.monitor.os.Memory
     * @author: fengt
     * @date: 2021/7/19 15:54
     **/
    private Memory getMemoryInfo(GlobalMemory m) {
        Memory memory = new Memory();
        memory.setTotal(m.getTotal());
        memory.setUsed(m.getTotal() - m.getAvailable());
        memory.setFree(m.getAvailable());
        return memory;
    }

    /**
     * 操作系统信息
     * @return: com.min.monitor.os.ServerSystem
     * @author: fengt
     * @date: 2021/7/19 15:54
     **/
    private ServerSystem getSystemInfo() {
        ServerSystem sys = new ServerSystem();
        Properties props = System.getProperties();
        sys.setName(IpUtils.getHostName());
        sys.setIp(IpUtils.getHostIp());
        sys.setOsName(props.getProperty("os.name"));
        sys.setOsArch(props.getProperty("os.arch"));
        sys.setProjectDir(props.getProperty("user.dir"));
        return sys;
    }

    /**
     * JVM信息
     * @return: com.min.monitor.os.Jvm
     * @author: fengt
     * @date: 2021/7/19 15:54
     **/
    private Jvm getJvmInfo() {
        Jvm jvm = new Jvm();
        Properties props = System.getProperties();
        jvm.setTotal(Runtime.getRuntime().totalMemory());
        jvm.setMax(Runtime.getRuntime().maxMemory());
        jvm.setFree(Runtime.getRuntime().freeMemory());
        jvm.setVersion(props.getProperty("java.version"));
        jvm.setHome(props.getProperty("java.home"));
        return jvm;
    }

    /**
     * 磁盘信息
     * @param os:
     * @return: java.util.List<com.min.monitor.os.ServerDisk>
     * @author: fengt
     * @date: 2021/7/19 15:54
     **/
    private List<ServerDisk> getDiskInfo(OperatingSystem os) {
        List<ServerDisk> disks = new LinkedList<ServerDisk>();
        FileSystem fileSystem = os.getFileSystem();
        List<OSFileStore> fsArray = fileSystem.getFileStores();
        for (OSFileStore fs : fsArray) {
            long free = fs.getUsableSpace();
            long total = fs.getTotalSpace();
            long used = total - free;
            ServerDisk sysFile = new ServerDisk();
            sysFile.setDirName(fs.getMount());
            sysFile.setFileSystem(fs.getType());
            sysFile.setTypeName(fs.getName());
            sysFile.setTotal(convertByteToUnit(total));
            sysFile.setFree(convertByteToUnit(free));
            sysFile.setUsed(convertByteToUnit(used));
            sysFile.setUsage(ExactDecimalUtil.mul(ExactDecimalUtil.div(used, total, 4), 100));
            disks.add(sysFile);
        }
        return disks;
    }

    /**
     * 字节转换为带单位数值
     * @param size:
     * @return: java.lang.String
     * @author: fengt
     * @date: 2021/7/19 15:55
     **/
    private String convertByteToUnit(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else {
            return String.format("%d B", size);
        }
    }
}
